package com.xquant.pricing.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

import java.io.*;
import java.util.*;

public class FileXmlUtil {

    public static String readFile(String path) {
        String line = "";
        String[] arrs = null;
        StringBuffer sb = new StringBuffer();

        try {
            FileReader fr = new FileReader(path);
            BufferedReader br = new BufferedReader(fr);
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            br.close();
            fr.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return sb.toString();
    }

    public static JSONObject xml2JSON(byte[] xml) {
        JSONObject json = new JSONObject();
        try {
            InputStream is = new ByteArrayInputStream(xml);
            SAXBuilder sb = new SAXBuilder();
            org.jdom2.Document doc = sb.build(is);
            Element root = doc.getRootElement();
            json.put(root.getName(), iterateElement(root));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JDOMException e) {
            e.printStackTrace();
        }

        return json;
    }

    private static JSONObject iterateElement(Element element) {
        List node = element.getChildren();
        Element et = null;
        JSONObject obj = new JSONObject();
        List list = null;
        for (int i = 0; i < node.size(); i++) {
            list = new LinkedList();
            et = (Element) node.get(i);
            if (et.getTextTrim().equals("")) {
                if (et.getChildren().size() == 0)
                    continue;
                if (obj.containsKey(et.getName())) {
                    list = (List) obj.get(et.getName());
                }
                list.add(iterateElement(et));
                obj.put(et.getName(), list);
            } else {
                if (obj.containsKey(et.getName())) {
                    list = (List) obj.get(et.getName());
                }
                list.add(et.getTextTrim());
                obj.put(et.getName(), list);
            }
        }
        return obj;
    }

    /**
     * json转xml<br>
     * 方 法 名：jsonToXml <br>
     * 创 建 人：h.j<br>
     * 创建时间：2017年5月10日 上午11:09:26 <br>
     * 修 改 人： <br>
     * 修改日期： <br>
     *
     * @param json
     * @return String
     */
    public static String jsonToXml(String json, String agrmt, String version, String senderCode, String receiverCode, String sendDate, String fileNumber, String busiDataType, String operationType) {
        try {
            JSONArray jsonArray = JSON.parseArray(json);
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                jsonObject.remove("REPORT_DATE");
            }
            StringBuffer buffer = new StringBuffer();
            buffer.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
            buffer.append("<Root>  <Header> <Version>" + version + "</Version> <SenderCode>" + senderCode + "</SenderCode> " +
                    "<ReceiverCode>" + receiverCode + "</ReceiverCode> <SendDate>" + sendDate + "</SendDate> <FileNumber>" +
                    fileNumber + "</FileNumber> " + "<BusiDataType>" + busiDataType + "</BusiDataType>  <OperationType>" +
                    operationType + "</OperationType> " + "</Header><Body> ");
            for (int i = 0; i < jsonArray.size(); i++) {
                StringBuffer sonBuffer = new StringBuffer();
                JSONObject jObj = jsonArray.getJSONObject(i);
                sonBuffer.append("<" + agrmt + ">");
                jsonToXmlstr(jObj, sonBuffer);
                sonBuffer.append("</" + agrmt + ">");
                buffer.append(sonBuffer);
            }
            buffer.append("</Body>");
            buffer.append("</Root>");
            return buffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * json转str<br>
     * 方 法 名：jsonToXmlstr <br>
     * 创 建 人：h.j <br>
     * 创建时间：2017年5月10日 下午12:02:17 <br>
     * 修 改 人： <br>
     * 修改日期： <br>
     *
     * @param jObj
     * @param buffer
     * @return String
     */
    public static String jsonToXmlstr(JSONObject jObj, StringBuffer buffer) {
        Set<Map.Entry<String, Object>> se = jObj.entrySet();
        for (Iterator<Map.Entry<String, Object>> it = se.iterator(); it.hasNext(); ) {
            Map.Entry<String, Object> en = it.next();
            if (en.getValue() == null) {
                buffer.append("<" + en.getKey() + ">" + en.getValue());
                buffer.append("</" + en.getKey() + ">");
            } else {
                if (en.getValue().getClass().getName().equals("com.alibaba.fastjson2.JSONObject")) {
                    buffer.append("<" + en.getKey() + ">");
                    JSONObject jo = jObj.getJSONObject(en.getKey());
                    jsonToXmlstr(jo, buffer);
                    buffer.append("</" + en.getKey() + ">");
                } else if (en.getValue().getClass().getName().equals("com.alibaba.fastjson2.JSONArray")) {
                    JSONArray jarray = jObj.getJSONArray(en.getKey());
                    for (int i = 0; i < jarray.size(); i++) {
                        buffer.append("<" + en.getKey() + ">");
                        JSONObject jsonobject = jarray.getJSONObject(i);
                        jsonToXmlstr(jsonobject, buffer);
                        buffer.append("</" + en.getKey() + ">");
                    }
                } else {
                    buffer.append("<" + en.getKey() + ">" + en.getValue());
                    buffer.append("</" + en.getKey() + ">");
                }
            }
        }
        return buffer.toString();
    }

    public static void writeStringFile(String Data, String filePath) {
        BufferedReader bufferedReader = null;
        BufferedWriter bufferedWriter = null;
        File distFile = null;
        try {
            distFile = new File(filePath);
            if (!distFile.getParentFile().exists())
                distFile.getParentFile().mkdirs();
            bufferedReader = new BufferedReader(new StringReader(Data));
            bufferedWriter = new BufferedWriter(new FileWriter(distFile));
            char buf[] = new char[1024]; // 字符缓冲区
            int len;
            while ((len = bufferedReader.read(buf)) != -1) {
                bufferedWriter.write(buf, 0, len);
            }
            bufferedWriter.flush();
            bufferedReader.close();
            bufferedWriter.close();
        } catch (Exception e) {
            writeStringFile(Data, filePath);
        }
    }

    public static Map sendMap() {
        Map map = new HashMap();
        map.put("A1001", "MasterAgrmt");
        map.put("A1002", "MasterAgrmtProduct");
        map.put("A1003", "SupAgrmt");
        map.put("A1004", "PerformanceGuaranteeAgrmt");
        map.put("A1005", "OptionConfirmation");
        map.put("A1006", "SwapConfirmation");
        map.put("A1007", "OptionTermination");
        map.put("A1008", "SwapTermination");
        map.put("A1009", "SwapTermination");
        map.put("A1010", "SwapTermination");
        map.put("A1011", "SwapTermination");
        map.put("A1012", "SwapTermination");
        map.put("A1013", "SwapTermination");
        return map;
    }
}
